Public Class frmMainView

    Private WithEvents dgvBrowser As WRDB.Controls.DGVEditor
    Const MaxRecords = 1000
    Private Initializing As Boolean = True

    ''' <summary>
    ''' Execute query so that the same data you select on map are available for reports, etc.
    ''' </summary>
    Private Sub ExecuteQuery()
        Try
            If Initializing Or lstStations.Text = "" Or lstPCodes.Text = "" Or dtEndDate.Value <= dtStartDate.Value Then Exit Sub
            WriteProgress("Selecting records...", ProgressBarStyle.Marquee)
            Dim sqlWhere As String = String.Format("WHERE Date_Time BETWEEN {0} AND {1}", Project.DB.DateTime(dtStartDate.Value), Project.DB.DateTime(dtEndDate.Value))
            If lstStations.SelectedIndex <> 0 Then sqlWhere &= String.Format(" AND Station_ID = '{0}'", Project.DB.GetPickList(lstStations))
            If lstPCodes.SelectedIndex <> 0 Then sqlWhere &= String.Format(" AND PCode = '{0}'", Project.DB.GetPickList(lstPCodes))
            Dim SQL As String = String.Format("SELECT * FROM {0} {1}", lstTables.Text, sqlWhere)
            MainForm.SelectData(SQL)
            FillGrid()
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub chkRefresh_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkRefresh.CheckedChanged
        If chkRefresh.Checked Then
            If btnRefresh.Enabled Then btnRefresh.PerformClick()
            btnRefresh.Enabled = False
        End If
    End Sub

    Private Sub FillLists()
        Try
            Initializing = True
            WriteProgress("Filling lists...", ProgressBarStyle.Marquee)
            Project.DB.FillPickList(lstStations, lstTables.Text, "Stations", "Station_ID", "Station_Name", "(All)", , Project.SupportDir)
            Project.DB.FillPickList(lstPCodes, lstTables.Text, "PCodes", "PCode", "Anal_Name", "(All)", , Project.SupportDir)
            dtStartDate.Value = TestNull(Project.DB.ExecuteScalar("SELECT MIN(Date_Time) FROM {0}", lstTables.Text), "1/1/1900")
            dtEndDate.Value = TestNull(Project.DB.ExecuteScalar("SELECT MAX(Date_Time) FROM {0}", lstTables.Text), "1/1/2100")
            MainWRDB.CloseSplashScreen()
            Initializing = False
            If chkRefresh.Checked Then
                ExecuteQuery()
            Else
                btnRefresh.Enabled = True
            End If
        Catch ex As Exception
            ErrorMsg(, ex)
        Finally
            ProgressComplete()
        End Try
    End Sub

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        mnuMain.Visible = False
        tbMain.Visible = False
        GetWindowPos(REGAPP, Me)
        Initializing = True
        chkRefresh.Checked = GetSetting(REGAPP, "General", "AutoRefresh", False)
        cboProjects.Items.AddRange(IniFile.GetProjectNames.ToArray)
        If Project IsNot Nothing Then cboProjects.Text = Project.Name
        dgvBrowser = New WRDB.Controls.DGVEditor(dgBrowser)

        'convenient means to add menu handlers so don't have to have so many methods
        CheckSplitButtonMenus(Me)
    End Sub

    Private Sub CheckSplitButtonMenus(ByVal Container As Control)
        For Each cntl As Control In Container.Controls
            If TypeOf cntl Is WRDB.Controls.SplitButton Then
                With CType(cntl, WRDB.Controls.SplitButton)
                    For Each item As ToolStripItem In .ContextMenuStrip.Items
                        If TypeOf item Is ToolStripMenuItem Then AddMenuHandler(item)
                    Next
                End With
            End If
            CheckSplitButtonMenus(cntl)
        Next
    End Sub

    Private Sub frmMainMW_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        SaveSetting(REGAPP, "General", "AutoRefresh", chkRefresh.Checked)
        SaveWindowPos(REGAPP, Me)
    End Sub

    Private Sub lstTables_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstTables.SelectedIndexChanged
        If lstTables.SelectedIndex >= 0 Then
            If CheckTableStructure(lstTables.Text) Then
                FillLists()
            Else
                lstTables.SelectedIndex = -1
            End If
        End If
    End Sub

    Private Sub cboProjects_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboProjects.SelectedIndexChanged
        SetProject(cboProjects.Text)
        lstTables.Items.Clear()
        lstTables.Items.AddRange(Project.GetTableList(clsProject.enumTableTypes.Working, clsProject.enumTableTypes.Master).ToArray)
        lstStations.Items.Clear()
        lstStations.Items.Add("(All)")
        lstPCodes.Items.Clear()
        lstPCodes.Items.Add("(All)")
        dtStartDate.Value = Now
        dtEndDate.Value = Now
    End Sub

    Friend Sub FillGrid()
        GetDataSource()
        FinishFillGrid()
    End Sub

    Private Sub GetDataSource()
        Try
            With Project
                ' set up SQL statement
                Dim sql As String
                Dim fldlist As String = "Station_ID,Date_time,PCode,LEW_Pct,Depth_M,Agency,CCode,RCode,Result,Validated,Track_ID"
                Select Case .DB.DatabaseType
                    Case clsDB.enumDBType.Firebird, clsDB.enumDBType.Firebird_Embedded
                        sql = String.Format("SELECT FIRST {1} {2} FROM {0}", clsProject.TempData, MaxRecords, fldlist)
                    Case clsDB.enumDBType.SQLite, clsDB.enumDBType.MySQL
                        sql = String.Format("SELECT {2} FROM {0} LIMIT {1}", clsProject.TempData, MaxRecords, fldlist)
                    Case clsDB.enumDBType.Oracle
                        sql = String.Format("SELECT {2} FROM {0} WHERE CAST(ROWNUM AS INTEGER)<={1}", clsProject.TempData, MaxRecords, fldlist)
                    Case Else
                        sql = String.Format("SELECT TOP {1} {2} FROM {0}", clsProject.TempData, MaxRecords, fldlist)
                End Select

                ' retrieve data into DataSet
                If .DataSet Is Nothing Then .DataSet = New DataSet
                If .DataSet.Tables.Contains("Temporary") Then .DataSet.Tables("Temporary").Clear()
                If Not Project.ResetPDox(clsProject.TempData) Then Exit Sub
                .DB.AddTable(.DataSet, "Temporary", sql)
                ProgressComplete()
                Try
                    .SetTableHeadings(clsProject.enumTableTypes.Temporary)
                Catch ex As Exception
                    WarningMsg(ex.Message)
                End Try
            End With
        Catch ex As Exception
            ErrorMsg(, ex)
        Finally
        End Try
    End Sub

    Private Sub FinishFillGrid()
        Try
            With dgBrowser
                .SuspendLayout()
                .DataSource = Nothing
                .Font = New Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point)
                .AllowUserToOrderColumns = False
                .AllowUserToResizeColumns = True
                .AllowUserToResizeRows = False
                .AllowUserToDeleteRows = False
                .AllowUserToAddRows = False
                .RowHeadersVisible = False
                .ReadOnly = True
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect

                .ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single
                .StandardTab = False

                Dim dt As DataTable = Project.DataSet.Tables("Temporary")
                If dt Is Nothing Then Exit Sub

                .DataSource = dt

                For c As Int16 = 0 To .Columns.Count - 1
                    With .Columns(c)
                        .HeaderText = dt.Columns(c).Caption
                        .SortMode = DataGridViewColumnSortMode.NotSortable
                        If dt.Columns(c).DataType Is GetType(String) Then
                            .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
                        ElseIf dt.Columns(c).DataType Is GetType(Boolean) Then
                            .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                        ElseIf dt.Columns(c).DataType Is GetType(Date) Then
                            .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
                            .DefaultCellStyle.Format = MyDateTimeFormat()
                        Else
                            .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                        End If
                    End With
                    Application.DoEvents()
                Next

                .EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2  'want to be able to do global editing (double-click to enter is OK)
                dgvBrowser.AutoFillSelectedCells = True

                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                .ColumnHeadersDefaultCellStyle.WrapMode = DataGridViewTriState.False
                .AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
                .ResumeLayout(True)
            End With

            'must reset modified flag in editor
            dgvBrowser.IsModified = False
            dgvBrowser.AutoFillSelectedCells = False
            WriteStatus(String.Format("{0} of {1} records were selected (first {2} are displayed)", Project.DB.GetRecordCount(clsProject.TempData), Project.DB.GetRecordCount(lstTables.Text), MaxRecords))
        Catch ex As Exception
            ErrorMsg(, ex)
        Finally
            'IniFile.SaveAndClose()
        End Try
    End Sub

    Private Sub btnRefresh_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
        ExecuteQuery()
        btnRefresh.Enabled = False
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        WriteProgress("Closing...")
        Enabled = False
        Close()
    End Sub

    Private Sub lst_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstStations.SelectedIndexChanged, lstPCodes.SelectedIndexChanged, dtStartDate.ValueChanged, dtEndDate.ValueChanged
        'If Initializing Then Exit Sub
        btnRefresh.Enabled = True
        If chkRefresh.Checked Then
            btnRefresh.PerformClick()
        End If
    End Sub

    Private Sub btnReport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReport.Click
        mnuRptStaPCode.PerformClick()
    End Sub

    Private Sub btnSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelect.Click
        mnuSelectMap.PerformClick()
    End Sub

    Private Sub btnGraph_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGraph.Click
        mnuGraphTS.PerformClick()
    End Sub

    Private Sub btnMap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMap.Click
        mnuOutputGIS.PerformClick()
    End Sub

    Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
        mnuExportText.PerformClick()
    End Sub

    Private Sub mnuConfigFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuConfigFile.Click
        With New FolderBrowserDialog
            .ShowNewFolderButton = True
            AppDataPath = GetSetting(REGAPP, "General", "AppDataPath", AppDataPath)
            .SelectedPath = AppDataPath
            If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                AppDataPath = .SelectedPath
                SaveSetting(REGAPP, "General", "AppDataPath", AppDataPath)
                MainWRDB = New WRDB.Lib.clsWRDB
                cboProjects.Items.AddRange(IniFile.GetProjectNames.ToArray)
                If cboProjects.Items.Count > 0 Then cboProjects.SelectedIndex = 0
            End If
            .Dispose()
        End With
    End Sub

    Private Sub mnuSelectMap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSelectMap.Click
        Try
            Dim lst As New Generic.List(Of String)
            MainForm.CheckGisData()
            With New WRDB.GIS.frmGIS(Project, ActiveTableName, clsProject.TempData, GIS.frmGIS.enumMode.SelectStations, MainWRDB.WRDBStationTypes, Project.GisBasemapStations)
                If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                    lst = .SelectedStations
                End If
                .Dispose()
            End With
            If lst.Count = 0 Then Exit Sub
            Initializing = True
            With lstStations
                .SelectedItems.Clear()
                For Each s As String In lst
                    For i As Integer = 0 To lstStations.Items.Count - 1
                        If Project.DB.GetPickList(.Items(i)) = s Then .SelectedItems.Add(.Items(i))
                    Next
                Next
            End With
            Initializing = False
            btnRefresh.Enabled = True
            btnRefresh.PerformClick()
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub
End Class
